from flask import Flask,request
from flask_cors import CORS
import jwt
from config import BaseConfig
from db import db
from socketIO import socketIO as socketio
from entity.Response import success,error,authority
import os
os.environ["TOKENIZERS_PARALLELISM"] = "false"

from controller.LoginController import loginController, jwt_secret_key
from controller.ModelController import modelController
from controller.TalkController import talkController
from controller.DataController import dataController
from controller.InfoController import infoController
from controller.QuestionController import questionController
from controller.VideoController import videoController
from controller.DrugController import drugController
from controller.StreamController import streamController

app = Flask(__name__)
app.json.ensure_ascii = False # 解决中文乱码问题
CORS(app)
app.config.from_object(BaseConfig)
db.init_app(app)
socketio.init_app(app, cors_allowed_origins='*',async_mode='threading') # 用socketio初始化flask的app

app.register_blueprint(loginController, url_prefix='')
app.register_blueprint(modelController, url_prefix='/model')
app.register_blueprint(talkController, url_prefix='/talk')
app.register_blueprint(dataController, url_prefix='/data')
app.register_blueprint(infoController, url_prefix='/info')
app.register_blueprint(questionController, url_prefix='/question')
app.register_blueprint(videoController, url_prefix='/video')
app.register_blueprint(drugController, url_prefix='/drug')
app.register_blueprint(streamController, url_prefix='/stream')

# 路径白名单
allow_paths = ['/login','/register','/getPhoneCode',
               '/model/uploadCsv','/model/uniappUploadImage','/model/uniappUploadBatchImage','/model/uploadBatchImage','/model/uploadImage','/model/downloadCsv','/model/enhanceImage','/model/getProbList',
               '/info/imageToOSS','/info/batchImageToOSS',
               '/data/downloadPdfTemplate','/drug/exportDrug','/data/parsePdf',
               '/data/getAgeListFromInfoTable','/data/getHotDiseaseFromQuestionTable','/data/getWordCloudFormQuestionTable']

# 全局方法 在请求之前先校验是否含有jwt
@app.before_request
def before_request():
    path = request.path
    if path in allow_paths:
        return None
    # 获取token
    token = request.cookies.get('token')
    if not token:
        token = request.headers.get('token')
    if not token:
        return authority(message='鉴权失败，请先登录！')
    try:
        decoded_payload = jwt.decode(token, jwt_secret_key, algorithms=['HS256'])
    except jwt.ExpiredSignatureError:
        return authority(message='token已过期，请重新登录！')
    except jwt.InvalidTokenError:
        return authority(message='无效token')
    return None

if __name__ == '__main__':
    import matplotlib
    matplotlib.use('Agg')
    app.run(debug=True,port=5000)